const defaultAvatarUrl = 'https://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRna42FI242Lcia07jQodd2FJGIYQfG0LAJGFxM4FbnQP6yfMxBgJ0F3YRqJCJ1aPAK2dQagdusBZg/0'

Page({
  data: {
    openId: '',
    avatarUrl: defaultAvatarUrl,
    nickName: ''
  },
  onLoad(options) {
    const { avatarUrl, nickName } = getApp().globalData.userInfo
    this.setData({ 
      openId: options?.openId,
      avatarUrl,
      _avatarUrl: avatarUrl, // 该路径存储云
      nickName
     });
  },
  async onChooseAvatar(e) {
    const { avatarUrl } = e.detail 
    const _this = this;
   try {
    const resp = await wx.cloud.uploadFile({
      // 指定上传到的云路径
      cloudPath: 'my-avatar.png',
      // 指定要上传的文件的小程序临时文件路径
      filePath: avatarUrl,
      config: {
        env: 'mock-weather-6g2jv4s1cede9cfc'
      }
    })
    console.log(resp)
    _this.setData({
      avatarUrl,
      _avatarUrl: resp.fileID,
    })
   } catch (error) {
     console.error(error)
   }
  },
  bindsubmit(e) {
    const { nickName } = e.detail.value;
    const params = {
      openId: this.data.openId,
      avatarUrl: this.data._avatarUrl,
      nickName,
    }
    console.log(params)
    const _this = this;
    // 请求云函数修改
     wx.cloud.callFunction({
      name: 'quickstartFunctions',
      config: {
        env: 'mock-weather-6g2jv4s1cede9cfc'
      },
      data: {
        type: 'updateUser',
        data: params
      }
    }).then((res) => {
        if (res?.result?.success) {
          getApp().globalData.userInfo.avatarUrl = _this.data.avatarUrl;
          getApp().globalData.userInfo.nickName = nickName;
          wx.showToast({
            title: '保存成功',
          })
          wx.navigateBack()
        }
    }).catch(e => {
      console.error(e)
      wx.showToast({
        title: '操作失败',
        icon: 'error'
      })
    })

  }
})